package fr.dauphine.td3.ctl;

import java.io.IOException;

import fr.dauphine.td3.bdd.EmployeDAO;
import fr.dauphine.td3.emp.Employe;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("user/employe")	
public class EmployeController {
	
	@Autowired
	private EmployeValidator employeValidator;
	
	@Autowired
	private EmployeDAO employeDAO;

	@RequestMapping(method=RequestMethod.POST)
	public String validation (@ModelAttribute("employe") Employe emp, BindingResult result, @RequestParam("fichier") MultipartFile fichier, ModelMap model) {
		
		if (emp.getId().length() != 0 && emp.getId() != "-1") {
			
			Employe empPhoto = employeDAO.get(emp.getId());
			
			if (empPhoto.getPhoto().length != 0) {
				emp.setPhoto(empPhoto.getPhoto());
			} else {
				try {
					emp.setPhoto(fichier.getBytes());
				} catch (IOException e) {
					System.out.println("erreur enregistrement photo");
					e.printStackTrace();
				}
			}	
		} else {
			try {
				emp.setPhoto(fichier.getBytes());
			} catch (IOException e) {
				System.out.println("erreur enregistrement photo");
				e.printStackTrace();
			}
		}
		
		employeValidator.validate(emp, result);
		
		if (result.hasErrors()) {
			System.out.println("erreur formulaire");
			return "employe";
		} else {	
			employeDAO.save(emp);
			model.addAttribute("employe", emp);
		}	
		
		return "redirect:user/employes.html";
	}
	
	@RequestMapping(method=RequestMethod.GET)
	public String affichage(@RequestParam(value="id", required = false) String id, ModelMap model) {
		
		Employe e = null;
		
		if (!id.equals("-1")) {
			e = employeDAO.get(id);
		}
		else {
			e = new Employe();
		}
		
		model.addAttribute("employe", e);
		
		return "employe";
		
	}
	
}
	
